package scau.erps.service.impl;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.service.IdEntityService;

import erps.erps.amq.Sender;
import scau.erps.app.Erps;
import scau.erps.entity.FreeMarket;
import scau.erps.entity.Product;
import scau.erps.entity.Research;
import scau.erps.entity.Sand;
import scau.erps.entity.Store;
import scau.erps.service.FreeMarketService;
import scau.erps.service.ProductService;
import scau.erps.service.ResearchService;
import scau.erps.service.SandService;
import scau.erps.service.StoreService;

/** 
 * 自由市场服务类
 * @author outsider
 * 
 */
public class FreeMarketServiceImpl extends IdEntityService<FreeMarket> implements FreeMarketService{

	/**
	 * 发布出售信息
	 * 返回代码 
	 * 0：发布成功
	 * -1:原材料不足
	 * -2:价格不合理
	 * -5:成品不足
	 * -6:出售原材料数量为偶数
	 * @return 
	 */
	public int add(FreeMarket freeMarket) {
		String type=freeMarket.getType();
		String product=freeMarket.getProduct();
		int teamId=Erps.getCurrentTeam().getId();
		
		
		int price=freeMarket.getPrice()/freeMarket.getNum();
		int cost=getCost(product, type);
		if ("Material".equals(type)){
			StoreService storeServices=Erps.getIocInstance().get(StoreServiceImpl.class);
			SandService sandService=Erps.getIocInstance().get(SandServiceImpl.class);
			int num=freeMarket.getNum();
			if(num % 2!=0) return -6;
			Store store=storeServices.getStoreByTeamId(teamId);
			int M1=store.getM1();
			int M2=store.getM2();
			int M3=store.getM3();
			int M4=store.getM4();
			if ("M1".equals(product)){
				M1=M1-num;
				if (M1<0) return -1;
				store.setM1(M1);
			}
			if ("M2".equals(product)){
				M2=M2-num;
				if (M2<0) return -1;
				store.setM2(M2);
			}
			if ("M3".equals(product)){
				M3=M3-num;
				if (M3<0) return -1;
				store.setM3(M3);
			}
			if ("M4".equals(product)){
				M4=M4-num;
				if (M4<0) return -1;
				store.setM4(M4);
			}
			freeMarket.setBuyer(9);                             //自动完成原材料购买操作
			freeMarket.setBuydate(Erps.getSand().getTime());
			storeServices.updateStoreByTeamId(store);
			Sand sand = sandService.getSandByTeam(teamId);
			int cash = sand.getCash();
			sand.setCash(cash + num/2);
			sand.setOther(num/2);
			sandService.updateSand(sand);
			Sender.main(freeMarket);
		}
		else if("Product".equals(type)){
			ProductService productService=Erps.getIocInstance().get(ProductServiceImpl.class);
			product=freeMarket.getProduct();
			Product productE=null;
			if (price<Math.ceil(cost*1.5)||price>Math.ceil(cost*3.0)) return -2;
			List<Product> list=productService.getProductByTypeAndStatus(teamId, product, "成品");
			if (list.size()==0) return -5;
			productE=list.get(0);
			productE.setStatus("待售");  //TODO product的新状态 报账须做处理
			freeMarket.setNote(productE.getId());
			productService.updateProduct(productE);
			
		}
		else if("Research".equals(type)){
			if (price<Math.ceil(cost*1.5)||price>Math.ceil(cost*3.0)) return -2;
		}
		this.dao().insert(freeMarket);
		return 0;
	}

	/**
	 * 撤回出售信息
	 * 返回代码 
	 * true：撤回成功
	 * false：已被购买
	 * 
	 * @return 
	 */
	public boolean delete(int ID) {
		FreeMarket freeMarket=this.fetch(ID);
		if (freeMarket.getBuyer()!=0) return false; //TODO 当数组库int字段为空时返回？
		String type=freeMarket.getType();
		String product=freeMarket.getProduct();
		int teamId=Erps.getCurrentTeam().getId();
		
		
		if ("Material".equals(type)){
			StoreService storeServices=Erps.getIocInstance().get(StoreServiceImpl.class);
			int num=freeMarket.getNum();
			Store store=storeServices.getStoreByTeamId(teamId);
			int M1=store.getM1();
			int M2=store.getM2();
			int M3=store.getM3();
			int M4=store.getM4();
			if ("M1".equals(product)){
				M1=M1+num;
				store.setM1(M1);
			}
			if ("M2".equals(product)){
				M2=M2+num;
				store.setM2(M2);
			}
			if ("M3".equals(product)){
				M3=M3+num;
				store.setM3(M3);
			}
			if ("M4".equals(product)){
				M4=M4+num;
				store.setM4(M4);
			}
			storeServices.updateStoreByTeamId(store);
		}
		else if("Product".equals(type)){
			ProductService productService=Erps.getIocInstance().get(ProductServiceImpl.class);
			product=freeMarket.getProduct();
			Product productE=null;
			int note=freeMarket.getNote();
			
			productE=productService.getProductByID(note);
			productE.setStatus("成品");  
			
			productService.updateProduct(productE);
		}
		else if("Research".equals(type)){
			
		}
		this.dao().delete(freeMarket);
		return true;		
	}

	/**
	 * 购买操作
	 * 返回代码 
	 * 0：购买成功
	 * -1：被撤回
	 * -2：被其他组购买
	 * -3：现金不足
	 * -4：该研发已完成
	 * 
	 * @return 
	 */
	public int buy(int ID) {
		FreeMarket freeMarket=this.fetch(ID);
		if (freeMarket==null) return -1;
		if (freeMarket.getBuyer()!=0) return -2;
		
		SandService sandService=Erps.getIocInstance().get(SandServiceImpl.class);
		String type=freeMarket.getType();
		String product=freeMarket.getProduct();
		int price=freeMarket.getPrice();
		int buyerTeamId=Erps.getCurrentTeam().getId();
		Sand buyerSand=Erps.getSand();
		Sand sellerSand=sandService.getSandByTeam(freeMarket.getTeamId());
		int buyerCash=buyerSand.getCash();
		int sellerCash=sellerSand.getCash();
		if (buyerCash<price) return -3;

		if ("Material".equals(type)){
			StoreService storeServices=Erps.getIocInstance().get(StoreServiceImpl.class);
			int num=freeMarket.getNum();
			
			
			Store store=storeServices.getStoreByTeamId(buyerTeamId);
			int M1=store.getM1();
			int M2=store.getM2();
			int M3=store.getM3();
			int M4=store.getM4();
			if ("M1".equals(product)){
				M1=M1+num;
				store.setM1(M1);
			}
			if ("M2".equals(product)){
				M2=M2+num;
				store.setM2(M2);
			}
			if ("M3".equals(product)){
				M3=M3+num;
				store.setM3(M3);
			}
			if ("M4".equals(product)){
				M4=M4+num;
				store.setM4(M4);
			}
			storeServices.updateStoreByTeamId(store);
			freeMarket.setBuyer(buyerSand.getTeam_Id());
		}
		else if("Product".equals(type)){
			ProductService productService=Erps.getIocInstance().get(ProductServiceImpl.class);
			product=freeMarket.getProduct();
			Product productOld=null;
			Product productNew=new Product();
			int note=freeMarket.getNote();
			
			productOld=productService.getProductByID(note);
			productOld.setStatus("已交货");  
			
			productNew.setTeam_Id(buyerSand.getTeam_Id());
			productNew.setProduct(product);
			productNew.setLineNo(0);
			productNew.setLineType(productOld.getLineType());
			productNew.setManufacturingTime(productOld.getManufacturingTime());
			productNew.setCompleteTime(productOld.getCompleteTime());
			productNew.setCost(price); //对于买家成本为购买价
			productNew.setStatus("成品");
			
			this.dao().insert(productNew);
			productService.updateProduct(productOld);
			freeMarket.setBuyer(buyerSand.getTeam_Id());
		}
		else if("Research".equals(type)){
			ResearchService researchService=Erps.getIocInstance().get(ResearchServiceImpl.class);
			if (researchService.getResearchStatus(buyerTeamId, product)) return -4;
			
			Research research = new Research();
			int size=researchService.findResearchs(buyerTeamId, product);
			int need=0;
			if ("Crystal".equals(product)) need=4-size;
		    if ("Ruby".equals(product)) need=6-size;
		    if ("Saphire".equals(product)) need=8-size;
		    
			research.setTeam_Id(Erps.getCurrentTeam().getId());
			research.setType(product);
			research.setTime(Erps.getSand().getTime());
			research.setAmount(price);
			research.setName("产品研发");
		    for (int i=1; i<=need;i++) {
		    	if(i>=2)
		    		research.setAmount(0);
		    	researchService.researchInvest(research);
		    }
		    freeMarket.setBuyer(buyerSand.getTeam_Id());
		}
		buyerCash=buyerCash-price;
		sellerCash=sellerCash+price;
		buyerSand.setCash(buyerCash);
		sellerSand.setCash(sellerCash);
		sellerSand.setNon_operating_Income(price);//报表额外净利润
		freeMarket.setBuydate(buyerSand.getTime());//购买时间
		sandService.updateSand(buyerSand);
		sandService.updateSand(sellerSand);
		this.dao().update(freeMarket);
		Sender.main(freeMarket);
		return 0;		
	}


	@Override
	public List<FreeMarket> getFreeMarketByType(String type) {
		SqlExpressionGroup e1 = null;
		if (type!=null){
			e1 = Cnd.exps("type", "=", type);	
		}
		return this.query(Cnd.where(e1),null);
	}
	private int getCost(String product,String type){
		if (product.equals("M1")||product.equals("M2")||product.equals("M3")||product.equals("M4"))
			return 1;
			
		if (product.equals("Beryl")){	
		    return 2;
		}
		if (product.equals("Crystal")){	
		    return 4;
		}
		if (product.equals("Ruby")){
			if (type.equals("Product")) return 4;
			if (type.equals("Research")) return 12;
		}
		if (product.equals("Sapphire")){	
			if (type.equals("Product")) return 5;
			if (type.equals("Research")) return 18;
		}		
		return 0;
}

	@Override
	public List<FreeMarket> getBuyerMseeage(int teamid) {
		SqlExpressionGroup e1 = null;
		if(teamid != 0){
			e1 = Cnd.exps("teamId", "=", teamid);			
		}
		return this.query(Cnd.where(e1), null);
	}
	
}
